layui.define(['table', 'layer', 'cryptojs'], function (exports) {

    const $ = layui.jquery;
    const cryptojs = layui.cryptojs;

    const Class = function (id) {
        this.id = id;
    };

    //对外接口
    const request = function (id) {
        return new Class(id);
    };
    let existingLayerIndex = null;

    const setter = {
        tableName: 'layuiAdmin', //本地存储表名,
        request: {
            tokenName: 'token' //自动携带 token 的字段名（如：access_token）。可设置 false 不携带。
        },
        response: {
            statusName: 'code', //数据状态的字段名称
            statusSuccessCode: 0,
            statusLogoutCode: 1001,
            msgName: 'msg', //状态信息的字段名称
            dataName: 'data' //数据详情的字段名称
        }
    };

    request.saveToken = function(token){
        layui.data(setter.tableName, {key: setter.request.tokenName, value:token});
    };

    request.post = function (options) {
        const success = options.success, error = options.error, request = setter.request, response = setter.response;
        options.usData = options.data || {};
        options.data = {};
        //前台不能直接请求极舜科技服务器
        //if(options.isPlatform==null)options.isPlatform=false//是否请求极舜科技服务器
        options.headers = options.headers || {};
        options.headers["Content-Type"]= "application/json";
        if (options.showLoading == null) options.showLoading = true;
        if (options.isEncrypt == null) options.isEncrypt = true;
        if (options.showLoading) layer.load("正在获取数据，请稍等...");
        if (request.tokenName) {
            //如果传入TOKEN使用传入得TOKEN,否则去请求缓存中的TOKEN
            options.data[request.tokenName] = request.tokenName in options.data ? options.data[request.tokenName] : (layui.data(setter.tableName)[request.tokenName] || '');
            //自动给 Request Headers 传入 token
            options.headers[request.tokenName] = request.tokenName in options.headers ? options.headers[request.tokenName] : (layui.data(setter.tableName)[request.tokenName] || '');
        }
        if (options.isEncrypt) {
            options.headers["upload"] = false;
            options.headers["isEncrypt"]= true;
            options.data["body"] = cryptojs.encrypt(JSON.stringify(options.usData), options.headers[request.tokenName]);
        } else {
            options.headers["upload"] = options.upload == null ? true : options.upload;
            options.data = options.usData;
        }
        //加上这一个，让后台支持 application/json
        options.data = JSON.stringify(options.data);
        delete options.success;
        delete options.error;
        return $.ajax($.extend({
            type: "POST",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (res) {
                layer.closeAll('loading');
                ///#### 返回码判断区
                if (res[response.statusName] === response.statusSuccessCode) {
                    if (options.headers["isEncrypt"] != null && !options.headers["isEncrypt"]) {
                        res.data = JSON.parse(res.data);
                    } else {
                        if (res['token'] != null) layui.data(setter.tableName, {key: setter.request.tokenName, value: res['token']});
                        const token = (layui.data(setter.tableName)[request.tokenName] || '');
                        res.data = JSON.parse(cryptojs.decrypt(res['encData'], token));
                    }
                    typeof options.done === 'function' && options.done(res);
                } else {  //其它异常
                    const errorInfo = '<cite></cite> ' + (res[response.msgName] || '返回状态码异常');
                    layer.msg(errorInfo, {offset: 'auto', icon: 5,time:3000});
                }
                if(res.code===401){
                    setTimeout(function () {
                        if (existingLayerIndex !== null) {
                            layer.close(existingLayerIndex);
                        }
                        existingLayerIndex = layer.open({
                            type: 2,
                            title: '登录验证',
                            content: '/views/user/lverifyCode.html', // 替换为实际页面的 URL
                            area: ['600px', '300px'],
                            maxmin: true,
                            end: function() {
                                existingLayerIndex = null; // Reset the existingLayerIndex when the layer is closed
                            }
                        });
                    },1600)
                }
                typeof success === 'function' && success(res);
            },
            error: function (e, code) {
                layer.closeAll('loading');
                const errorInfo = '请求异常，请重试<br><cite>错误信息：</cite>' + code;
                layer.alert(errorInfo, {offset: 'auto', icon: 5,});
                typeof error === 'function' && error(e);
            },
        }, options));
    };
    exports('request', request);
});